package com.xike.microemailserver.controller;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.xike.entiy.ResultBean;
import com.xike.microemailserver.bean.FileInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * Auther: wuson  <br/>
 * Date: 2021/3/15:11:21  <br/>
 * Description:
 */
@Api(tags = "文件上传相关接口")
@RestController
@RequestMapping("/oss")
@Slf4j
public class OssController {
    @Resource
    private OSSClient ossClient;
    /**
     * 文件上传
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping(value = "/upload",produces = MediaType.APPLICATION_JSON_VALUE)
    public String upload(@RequestParam("file") MultipartFile file){
        String fileName = String.valueOf(new Date().getTime()).substring(6)+file.getOriginalFilename();
        // 上传文件流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            ossClient.putObject("wusong01", fileName, inputStream);
            //设置路径10年失效
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            URL url = ossClient.generatePresignedUrl("wusong01",fileName,expiration);
            //封装返回数据
            FileInfo fileInfo = FileInfo.builder().fileName(fileName).url(url.toString()).build();
            return JSONObject.toJSONString(ResultBean.builder().code(200).msg("上传成功").data(fileInfo).build());
        } catch (IOException e) {
            e.printStackTrace();
            return JSONObject.toJSONString(ResultBean.builder().code(1002).msg("上传失败").build());
        }
    }
    /**
     * 删除文件
     * @param fileName
     * @return
     */
    @PostMapping(value = "/delete",produces = MediaType.APPLICATION_JSON_VALUE)
    public String delete(String fileName){
        log.info("删除文件开始！！！");
        ossClient.deleteObject("wusong01",fileName);
        return JSONObject.toJSONString(ResultBean.builder().code(200).msg("删除成功").build());
    }
}
